import {Component, OnInit} from '@angular/core';
import {TableUtil} from '../../../util/table-util';
import {ResponseUtil} from '../../../util/response-util';
import {PageSubject} from '../../../util/page-subject';
import {DaAPI} from '../da-constants';
import {ActivatedRoute, Router} from '@angular/router';
import {DaVocsFileService} from './da-vocs-file.service';
import {MsgConstants} from '../../../constants/constants';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';

declare var $;
declare var moment;

@Component({
  selector: 'app-da-vocs-file',
  templateUrl: './da-vocs-file.component.html',
  styleUrls: ['./da-vocs-file.component.css']
})
export class DaVocsFileComponent implements OnInit {
  // 日期选择
  startDate = new Date(moment().subtract(1, 'w').format('YYYY/MM/DD'));
  endDate =  new Date();
  // 站点
  siteCode = '';
  rangeCode = '';
  // 设备
  deviceCode = '';
  // 组分数据

  isUpload = '0';

  table: any;
  siteArr: Array<any> = [];

  /**
   * 禁用日期数组
   * @type {any[]}
   */
  disabledDate: Array<any> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private vocsFileService: DaVocsFileService,
    private dialogService: OneDialogService,
    private tableUtil: TableUtil
  ) { }

  ngOnInit() {
    this.pushPage();
    this.initData();
    this.loadVocsOri();
    this.getSiteData();
  }
  /**
   * 面包屑导航
   */
  pushPage() {
    // const path = new Path('数据矫正', '');
    this.pageSubject.pushPage('数据校正', '查询');
  }

  /**
   * 初始化数据
   */
  initData() {
  }

  /**
   * 日期选择
   */
  startValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.startDate = null;
    //   this.dialogService.info('开始时间大于结束时间')
    // }
  };
  endValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.endDate = null;
    //   this.dialogService.info('结束时间小于开始时间')
    // }
  };
  disabledStartDate = (startValue) => {
    if (!startValue || !this.endDate) {
      return false;
    }
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= startValue.getTime()  && startValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime() || !isInRange;
    } else {
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime();
    }
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    const startDateTime =  new Date(moment(this.startDate).format('YYYY/MM/DD')).getTime();
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= endValue.getTime()  && endValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime || !isInRange;
    } else {
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime;
    }
  };

  loadVocsOri() {
    this.table = this.tableUtil.load('one_table_vocs-file',  {
      columns: [
        {field: 'sitename', title: '站点名称', valign: 'middle', align: 'left', halign: 'left'},
        {field: 'devicename', title: '设备名称', valign: 'middle', align: 'left', halign: 'left'},
        {field: 'filename', title: '文件名称', valign: 'middle', align: 'left', halign: 'left'},
        {field: 'filesize', title: '文件大小', valign: 'middle', align: 'left', halign: 'left'},
        {field: 'filetime', title: '文件上传时间', valign: 'middle', align: 'left', halign: 'left'},
        {field: 'oper', title: '操作', valign: 'middle', align: 'center', halign: 'center', formatter: this.operFormat, events:
            {'click .file-upload': this.uploadFile,
              'click .file-download': this.downloadFile,
              'click .file-delete': this.deleteFile
            }}
      ],
      idField: 'id',
      // sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10, 15, 50],
      paginationPreText: '上一页',
      paginationNextText: '下一页',
      singleSelect: false, // 多选
      clickToSelect: true, // 点击选中
      toolbar: '#one_operation_vocs-file',
      url: DaAPI.daVOCsFile,
      method: 'get',
      // 传递附加参数
      queryParams: (params) => {
        params.siteCode = this.siteCode;
        params.deviceCode = this.deviceCode;
        params.isUpload = this.isUpload
        params.dateStart = moment(this.startDate).format('YYYY-MM-DD HH');
        params.dateEnd =   moment(this.endDate).format('YYYY-MM-DD HH');
        return params;
      },
      // 返回数据处理器
      responseHandler: (result) => {
        if (result.data) {
          return result.data
        } else {
          return []
        }
      },
      height: 700, // table高度
      sortable: true,
      order: 'asc',
      classes: 'table table-hover',
      striped: true, // 隔行变色
      paginationLoop: false, // 是否开启循环分页
      mobileResponsive: true // 响应式
    });
  }

  /**
   * 格式化操作
   */
  operFormat = () => {
    return '<a class="file-upload">上传</a>&nbsp;&nbsp;<a class="file-download">下载</a>&nbsp;&nbsp;<a class="file-delete">删除</a>'
  };
  search () {
    if (this.startDate > this.endDate) {
      this.dialogService.info('开始时间大于结束时间，请重新选择');
    } else {
      this.tableUtil.refreshOptions();
    }
  }
  uploadFile = (e, value, row, index) => {
    this.router.navigate(['./upload',
      {siteCode: row.sitecode, deviceCode: row.devicecode, monitorTime: row.filename}
    ], {relativeTo: this.route})
  };
  downloadFile = (e, value, row, index) => {
    this.vocsFileService.downloadFile(row.sitecode + '_' + row.devicecode + '_' + row.filename).subscribe(
      result => this.processDownload(result, row.sitecode + '_' + row.devicecode + '_' + row.filename),
      error => this.responseUtil.error(error)
    )
  };
  processDownload(result, fileName) {
    const blob = new Blob([result]);
    this.saveAs(blob, fileName);
  }
  deleteFile = (e, value, row, index) => {
    this.dialogService.modalInfoWithCancelBtn('确定删除？', () => {
      this.vocsFileService.deleteFile(row.sitecode + '_' + row.devicecode + '_' + row.filename + '.a').subscribe(
        result => this.responseUtil.success(result, () => {
          if (result && result.code === MsgConstants.MSG_CODE_OK) {
            this.search();
          }
          if (result && result.code !== MsgConstants.MSG_CODE_OK) {
            this.dialogService.info(result.message);
          }
        }),
        error => this.responseUtil.error(error)
      )
    });
  };
  /**
   * 保存
   * @param  {Blob} blob
   * @param  {String} filename 想要保存的文件名称
   */
  saveAs = (blob, filename) => {

    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, filename);
    } else {
      const link = document.createElement('a');
      const body = document.querySelector('body');

      link.href = window.URL.createObjectURL(blob);
      link.download = filename;

      // fix Firefox
      link.style.display = 'none';
      body.appendChild(link);

      link.click();
      body.removeChild(link);

      window.URL.revokeObjectURL(link.href);
    }
  }
  /**
   * 获取站点数据
   */
  getSiteData = () => {
    this.vocsFileService.getSiteData().subscribe(
      result => this.responseUtil.success(result, this.progressD),
      error => this.responseUtil.error(error)
    )
  };
  progressD = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.siteArr = result.data;
        // this.siteCode = this.siteArr[0].SITECODE;
        // this.rangeCode = this.siteArr[0].RANGECODE;
        // this.changeSite(false);
      }
    } else {
      this.dialogService.info(result.message);
    }
  };
  changeSite = (isOpen) => {
    if (!isOpen) {
      if (this.rangeCode) {
        this.disabledDate = [];
        let site;
        this.siteArr.every((val) => {
          if (val.RANGECODE === this.rangeCode) {
            this.siteCode = val.SITECODE;
            site = val;
            return false
          } else {
            return true
          }
        });
        if (site.DATESTR && typeof site.DATESTR === 'string' ) {
          const dateArr = site.DATESTR.split(';');
          if (dateArr.length > 0) {
            dateArr.forEach((val) => {
              const singleDateArr = val.split(',');
              this.disabledDate.push({startDate: singleDateArr[0], endDate: singleDateArr[1]})
            });
            const dateLength = this.disabledDate.length;
            this.startDate = new Date(moment(this.disabledDate[dateLength - 1].startDate).format('YYYY/MM/DD HH:00'));
            this.endDate = new Date(moment(this.disabledDate[dateLength - 1].startDate).add('1', 'M').format('YYYY/MM/DD HH:00'));
          }
        }
      } else {
        this.disabledDate = [];
        this.siteCode = '';
      };
      this.search();
    }
  };
  changUploadStatus = (isOpen) => {
    if (!isOpen) {
      this.search();
    }
  }
}
